package com.yaodian100.mall.member.web;

import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.ec.member.entity.ImageValid;
import com.yaodian100.ec.member.entity.LoginHistory;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.shopping.entity.CartOrderProduct;
import com.yaodian100.ec.shopping.entity.CartOrderProductDetail;
import com.yaodian100.ec.shopping.entity.CartOrders;
import com.yaodian100.ec.shopping.service.CartOrdersService;
import com.yaodian100.mall.member.util.UserData;

public class NonMemberAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6967161774207296443L;

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private CartOrdersService cartOrdersService;

	@Autowired
	private MemberService memberService;

	private Member member;
	private String isFirst;
	private String mail;
	private String pwd;
	private String ccode;
	private String redirect_url;
	private String result;
	private String loginID;

	private int errTimes;

	public String tologin() throws Exception {
		if (isLogin()) {
			redirect_url = ServerValue.getFrontHostname() + ServerValue.getFrontContextPath() + "/member/myyaodian.do";
			return "loginOK";
		}
		errTimes = 0;
		return "tologin";
	}

	public String login() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		// get ip
		String host = request.getHeader("X-Forwarded-For");
		if (StringUtils.isBlank(host)) {
			host = request.getRemoteAddr();
		}
		String clientIp = StringUtils.isBlank(host) ? "" : (host.length() > 100 ? host.substring(0, 100) : host);

		member = memberService.getMemberByEmail(mail);

		if ("1".equals(isFirst)) { // ever buy
			if (null == member) {
				result = "unfind";
				return "tologin";
			}

			if (!"nonmember".equals(member.getApplySource())) {
				result = "ismember"; // 会员
				return "tologin";
			}

			if (errTimes > 3 && !checkCode(userData.getImageValid(), ccode)) {
				result = "code_error"; // 验证码错误
				memberService.saveFrontendLoginHistory(member, clientIp, "1");
				errTimes = memberService.getLoginHistorySize(member.getLoginId(), null, null);
				return "tologin";
			}

			if (null == memberService.loginPwdCheck(pwd, member)) {
				result = "pwd_error"; // 密码错误
				memberService.saveFrontendLoginHistory(member, clientIp, "2");
				errTimes = memberService.getLoginHistorySize(member.getLoginId(), null, null);
				return "tologin";
			}
			LoginHistory loginHistory = memberService.getLastLoginHistory(member.getLoginId());
			if (null != loginHistory) {
				member.setLastLoginTime(loginHistory.getLoginTime());
				memberService.update(member);
				memberService.deleteLoginHistory(member.getLoginId());
			}
			memberService.saveFrontendLoginHistory(member, clientIp);
			memberService.checkLoginBonus(member, request.getServerName(), userData.getApplySource());
			userData.setLoginId(member.getLoginId());
			userData.setMemberId(member.getMemberId());

			CartOrders cartOrders = cartOrdersService.getCart(member.getMemberId(), null);
			if (cartOrders != null) {
				cartOrdersService.cleanCartOrderNow(cartOrders.getCartId());
			}
			cartOrders = cartOrdersService.createCart(member.getMemberId(), null, null, null, 0, null, null);
			String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));

			processMoveTmpCartToCartOrder(tmpCartid, cartOrders.getCartId(), cartOrdersService, userData);
		} else { // first buy
			if (!checkCode(userData.getImageValid(), ccode)) {
				result = "code_error"; // 验证码错误
				return "tologin";
			}
			if (null != member) {
				if (!"nonmember".equals(member.getApplySource())) {
					result = "isregmember"; // 会员
					return "tologin";
				}
				result = "mail_exist";
				return "tologin";
			}
			member = new Member();
			member.setLoginId(mail);
			member.setEmail(mail);
			// member.setActiveDate(new Date());
			member.setPwd(pwd);

			member.setClientIp(clientIp);
			member.setApplySource("nonmember");
			member.setChannelChild("nonmember");
			String domainSrc = request.getServerName();
			member.setDomainSrc(domainSrc);
			member = memberService.saveNonMember(member);
			memberService.newBalance(member);
			autoLogin(memberService.getMemberByEmail(mail));
		}
		if (StringUtils.isBlank(redirect_url) || redirect_url.contains("/member/myCollection/")
				|| redirect_url.contains("/member/myBonus/") || redirect_url.contains("/member/myCoupon/")) {
			redirect_url = ServerValue.getFrontHostname();
		}
		return "loginOK";
	}

	public String goactivate() throws IOException {
		if (memberService.isLoginExist(loginID)) {
			result = "id_exist";
			return "jsonGoActivate";
		}
		member = memberService.getMemberByEmail(mail);
		member.setLoginId(loginID);
		memberService.saveMember(member);
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		userData.setLoginId(loginID);
		result = "ok";
		return "jsonGoActivate";
	}

	public String checkEmail() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		if (!checkCode(userData.getImageValid(), ccode)) {
			result = "code_error"; // 验证码错误
			return "jsonCheckEmail";
		}
		member = memberService.getMemberByEmail(mail);
		if (null != member) {
			if (!"nonmember".equals(member.getApplySource())) {
				result = "isregmember"; // 会员
				return "jsonCheckEmail";
			}
			result = "mail_exist";
			return "jsonCheckEmail";
		}
		result = "ok";
		return "jsonCheckEmail";
	}

	/**
	 * 檢查是否登入&是否為會員
	 * 
	 * @return
	 */
	public String checkLogin() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		loginID = userData.getLoginId();
		if (StringUtils.isBlank(loginID)) {
			result = "notLogin";
			return "jsonCheckLogin";
		}
		member = memberService.getMemberByLoginId(loginID, request.getServerName());
		if (null == member) {
			userData.clearAll();
			result = "notLogin";
			return "jsonCheckLogin";
		}
		if (!request.getServerName().equals(userData.getLoginDamain())) {
			// 登入domain不同, 强制登出
			userData.clearAll();
			result = "notLogin";
			return "jsonCheckLogin";
		}
		if (!"nonmember".equals(member.getApplySource())) {
			result = "login";
			return "jsonCheckLogin";
		}
		if (null != member.getActivateExpireDate()) {
			result = "waitActivate#" + member.getEmail() + "#" + member.getLoginId();
		} else {
			result = "needToActivate#" + member.getEmail();
		}
		return "jsonCheckLogin";
	}

	private boolean checkCode(String imageId, String inputCode) {
		ImageValid imageValid = new ImageValid();
		imageValid.setId(imageId);
		imageValid.setValidData(inputCode);
		try {
			memberService.isImageValid(imageValid);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	private void autoLogin(Member member) throws Exception {
		if (null != member) {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			// get ip
			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			String clientIp = StringUtils.isBlank(host) ? "" : (host.length() > 100 ? host.substring(0, 100) : host);

			UserData userData = new UserData(request, response);
			userData.clearAll();
			userData.setLoginId(member.getLoginId());
			userData.setMemberId(member.getMemberId());

			memberService.checkBalance(member);
			LoginHistory loginHistory = memberService.getLastLoginHistory(member.getLoginId());
			if (null != loginHistory) {
				member.setLastLoginTime(loginHistory.getLoginTime());
				memberService.update(member);
				memberService.deleteLoginHistory(member.getLoginId());
			}
			memberService.saveFrontendLoginHistory(member, clientIp);
			memberService.checkLoginBonus(member, request.getServerName(), userData.getApplySource());

			CartOrders cartOrders = cartOrdersService.getCart(member.getMemberId(), null);
			if (cartOrders != null) {
				cartOrdersService.cleanCartOrderNow(cartOrders.getCartId());
			}
			cartOrders = cartOrdersService.createCart(member.getMemberId(), null, null, null, 0, null, null);
			String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));

			processMoveTmpCartToCartOrder(tmpCartid, cartOrders.getCartId(), cartOrdersService, userData);
			logger.debug("autoLogin == " + new Date().toString() + "  host():" + host + ", apply source{}:"
					+ member.getApplySource() + ", loginId{}:" + member.getLoginId());
			// 记录购物车商品数量
			cartOrders = cartOrdersService.get(cartOrders.getCartId());
			userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
		}
	}

	private void processMoveTmpCartToCartOrder(String tmpCartid, String memberCartId,
			CartOrdersService cartordersService, UserData userData) throws Exception {
		// 若memberCartId為空，則新增一個cartOrders
		// logger.info("memberCartId:{}", memberCartId);
		CartOrders cartOrders = null;
		if (memberCartId == null) {
			cartOrders = cartordersService.createCart(userData.getMemberId(), null, null, null, 0, null, null);
			memberCartId = cartOrders.getCartId();
			userData.writeRawValue("cartid", cartOrders.getCartId());
			// memberCartId = createNewCartOrders(memberCartId, userData);
		} else {
			cartOrders = cartordersService.getCart(memberCartId, null);
		}
		// logger.info("cartOrders:{}", cartOrders);
		if (StringUtils.isNotBlank(tmpCartid)) {
			CartOrders tmpCart = cartordersService.get(tmpCartid);
			if (null != tmpCart) {

				// 將暫存的車移至cartOrderProduct
				for (CartOrderProduct cop : tmpCart.getCartOrderProducts()) {

					boolean isItemExists = false;
					for (CartOrderProduct memberCop : cartOrders.getCartOrderProducts()) {
						if (cop.getProdId().equals(memberCop.getProdId()) && cop.getProdSpecId().equals(memberCop.getProdSpecId())) {
							isItemExists = true;
							break;
						}
					}
					if (!isItemExists) {
						CartOrderProduct tmpcop = new CartOrderProduct();
						// tmpcop.setAmount(new BigDecimal(0.00));
						BeanUtils.copyProperties(cop, tmpcop, new String[] { "cartOrderProdId", "cartOrder", "coupon",
								"modifyDate", "details" });
						// logger.info("tmpcop:{}", tmpcop.getAmount());
						cartOrders.addCartOrderProduct(tmpcop);
						for (CartOrderProductDetail detail : cop.getDetails()) {
							CartOrderProductDetail cloneDetail = new CartOrderProductDetail();
							BeanUtils.copyProperties(detail, cloneDetail, new String[] { "cartOrderDetailId", "cartOrderProdId",
									"orderProduct", "cartId", "cartOrder", "modifyDate", "details" });
							tmpcop.addDetail(cloneDetail);

						}
					}
				}
				// 刪除暫存車的cartOrders
				cartordersService.save(cartOrders);
				cartordersService.delete(tmpCart);
			}
		}
	}

	private boolean isLogin() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);

		String tmp = userData.getLoginId();
		if (StringUtils.isNotBlank(tmp)) {
			member = memberService.getMemberByLoginId(tmp, request.getServerName());
		} else {
			return false;
		}
		if (member == null) {
			return false;
		}
		return true;
	}

	public void setCcode(String ccode) {
		this.ccode = ccode;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getIsFirst() {
		return isFirst;
	}

	public void setIsFirst(String isFirst) {
		this.isFirst = isFirst;
	}

	public String getRedirect_url() {
		return redirect_url;
	}

	public void setRedirect_url(String redirectUrl) {
		redirect_url = redirectUrl;
	}

	public String getResult() {
		return result;
	}

	public Member getMember() {
		return member;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public int getErrTimes() {
		return errTimes;
	}

	public void setErrTimes(int errTimes) {
		this.errTimes = errTimes;
	}

	public String getLoginID() {
		return loginID;
	}

	public void setLoginID(String loginID) {
		this.loginID = loginID;
	}

	public String getMail() {
		return mail;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}

}
